package com.cheksin.url;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import com.cheksin.entity.Goods;
import com.cheksin.excl.ReadExcelUtil;
import net.sf.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class YinBaoCookieUtil {

	public final static String CONTENT_TYPE = "Content-Type";

	public static void main(String[] args) {
		//exportImg("D:\\银豹图片下载",new File("D:\\商品资料.xlsx"));
	}
	public static String exportImg(String path,File file,Integer nameType){
		// login
		// 验证码的位置
		// Content content = getRandom("GET",
		// "http://localhost:8080/back/random.action", null, null, false,"d:/");

		String userCode = "qkx8888";
		String password = "qkx123456";
		String loginUrl = "https://beta44.pospal.cn/account/SignIn?noLog=";
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("userName", userCode);
		paramMap.put("password", password);
		paramMap.put("returnUrl", "");
		paramMap.put("screenSize", "1549*872");
		Content content = curl("POST", loginUrl, paramMap, null, false, "");
		System.out
				.println("第一次 content.getBody()= " + content == null ? "no body"
						: content.getBody());
		List<String> lsit = content.getHeaders().get("Set-Cookie");
		Map<String, String> resmap = new HashMap<String, String>();
		if (lsit != null) {
			StringBuffer sb = new StringBuffer();
			boolean isLast = false;
			int i = 0;
			for (String val : lsit) {
				i++;
				if (i == lsit.size()) {
					isLast = true;
				}
				int pos = val.indexOf("=");
				if (pos != -1) {
					String cookieName = val.substring(0, pos);
					String cookieVal = val.substring(pos + 1);
					System.out.println(cookieName + ":" + cookieVal);
					cookieVal = cookieVal.split(";")[0];
					if (isLast) {
						sb.append(cookieName + "=" + cookieVal);
					} else {
						sb.append(cookieName + "=" + cookieVal + ";");
					}
				}
			}
			System.out.println("sb.toString() = " + sb.toString());
			resmap.put("Cookie", sb.toString());
		}

		//获取列表
		String img = "https://beta44.pospal.cn/Eshop/LoadMatchProductsByPage";
		//参数
		paramMap = new HashMap<String, String>();
		paramMap.put("userId", "4568574");
		paramMap.put("categorysJson", "[]");
		paramMap.put("enable", "1");
		paramMap.put("productTagUid", "");
		paramMap.put("hasProductImage", "");
		paramMap.put("keyword", "");
		paramMap.put("pageIndex", "1");
		paramMap.put("pageSize", "430");
		paramMap.put("orderColumn", "");
		paramMap.put("asc", "false");

		System.out.println(resmap);
		content = curl("POST", img, paramMap, resmap, false, "");
		//System.out.println("第二次content.getBody() = "+content.getBody());
		JSONObject json = JSONObject.fromObject(content.getBody());
		String html = json.getString("contentView");
		Document doc = Jsoup.parse(html);
		Elements elements = doc.select("img");
		Map<String, String> map = new HashMap<String, String>();
		int i=0;
		//获取excl
		List<Goods> goods = ReadExcelUtil.readExcelInfo(file);
		Map<String, Goods> mapGoods = new HashMap<String, Goods>();
		for (Goods g : goods) {
			mapGoods.put(g.getTm(), g);
		}
		for (Element ele : elements) {
			String name = ele.attr("data-caption").trim();
			if(name != null && !"".equals(name)) {
				String src = src = ele.attr("data-src").trim();
				String tm = ele.attr("data-group").trim();
				tm = tm.replaceAll("dbImage_", "");
				String old_name = name;
				if(nameType == 1) {
					try {
						name = name.replaceAll("\\*", "X");
						name = name.replaceAll("（","(").replaceAll("）",")");
						name = name.substring(0,name.lastIndexOf("("));
					}catch (Exception e) {
						return "名称格式错误:"+old_name+"，"+e.toString();
					}
					++i;
					if(map.get(name) != null) {
						name = name + i;
					}
					//设置价格
					Goods g = mapGoods.get(tm);
					if(g == null) {
						continue;
					}
					name = name + "(市场价："+g.getScj()+"-现价："+g.getXsj()+")";
					//条码
					name = g.getTm();
					System.out.println(name);
					map.put(name, src);
				} else {
					if(map.get(tm) != null) {
						continue;
					}
					map.put(tm, src);
				}
			}
		}

		File filePath = new File(path);
		if (!filePath .exists() && !filePath .isDirectory()){
			filePath .mkdir();
		}
		StringBuffer info = new StringBuffer("");
		for (String key : map.keySet()) {
			info.append(download(map.get(key),key,path)+"\n");
		}
		return info.toString();
	}
	//java 通过url下载图片保存到本地
    public static String download(String urlString,String name,String path) {
        // 构造URL
        // 输入流
		InputStream is;
		FileOutputStream os;
		String filename ="";
		try {
			URL url = new URL(urlString);
			// 打开连接
			URLConnection con = url.openConnection();
			is = con.getInputStream();
			// 1K的数据缓冲
			byte[] bs = new byte[1024];
			// 读取到的数据长度
			int len;
			// 输出的文件流
			filename = path+"\\" + name + ".jpg";  //下载路径及下载图片名称

			File file = new File(filename);
			os = new FileOutputStream(file, true);
			// 开始读取
			while ((len = is.read(bs)) != -1) {
			    os.write(bs, 0, len);
			}
			// 完毕，关闭所有链接
	        os.close();
	        is.close();
			System.out.println(filename);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			return "1:"+e.toString();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			return "2:"+e.toString();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return "3:"+e.toString();
		}
		return filename;
    }

	public static Content curl(String method, // 方法类型
			String sUrl,// 要解析的URL
			Map<String, String> paramMap, // 存放用户名和密码的map
			Map<String, String> requestHeaderMap,// 存放COOKIE的map
			boolean isOnlyReturnHeader, String path) {// 存放文件路径
		System.out.println("-------------" + sUrl + "-------------------");
		Content content = null;
		HttpURLConnection httpUrlConnection = null;
		InputStream in = null;
		try {
			URL url = new URL(sUrl);
			boolean isPost = "POST".equals(method);

			if (method == null
					|| (!"GET".equalsIgnoreCase(method) && !"POST"
							.equalsIgnoreCase(method))) {
				method = "POST";
			}

			URL resolvedURL = url;
			URLConnection urlConnection = resolvedURL.openConnection();
			httpUrlConnection = (HttpURLConnection) urlConnection;
			httpUrlConnection.setRequestMethod(method);
			httpUrlConnection.setRequestProperty("Accept-Language",
					"zh-cn,zh;q=0.9");

			// Do not follow redirects, We will handle redirects ourself
			httpUrlConnection.setInstanceFollowRedirects(false);
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.setConnectTimeout(5000);
			urlConnection.setReadTimeout(5000);
			urlConnection.setUseCaches(false);
			urlConnection.setDefaultUseCaches(false);
			// set request header
			if (requestHeaderMap != null) {
				for (Map.Entry<String, String> entry : requestHeaderMap
						.entrySet()) {
					String key = entry.getKey();
					String val = entry.getValue();
					if (key != null && val != null) {
						urlConnection.setRequestProperty(key, val);
					}
				}
			}
			if (isPost) {
				urlConnection.setDoOutput(true);
				ByteArrayOutputStream bufOut = new ByteArrayOutputStream();
				boolean firstParam = true;
				for (Map.Entry<String, String> entry : paramMap.entrySet()) {
					String encName = URLEncoder.encode(entry.getKey(), "UTF-8");
					if (firstParam) {
						firstParam = false;
					} else {
						bufOut.write((byte) '&');
					}
					String encValue = URLEncoder.encode(entry.getValue(),
							"UTF-8");
					bufOut.write(encName.getBytes("UTF-8"));
					bufOut.write((byte) '=');
					bufOut.write(encValue.getBytes("UTF-8"));
				}
				byte[] postContent = bufOut.toByteArray();
				if (urlConnection instanceof HttpURLConnection) {
					((HttpURLConnection) urlConnection)
							.setFixedLengthStreamingMode(postContent.length);
				}
				OutputStream postOut = urlConnection.getOutputStream();
				postOut.write(postContent);
				postOut.flush();
				postOut.close();
			}
			httpUrlConnection.connect();
			int responseCode = httpUrlConnection.getResponseCode();

			// We handle redirects ourself
			if (responseCode == HttpURLConnection.HTTP_MOVED_PERM
					|| responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
				String location = httpUrlConnection.getHeaderField("Location");
				URL newAction = new URL(url, location);
				// Recurse
				StringBuffer newUrlSb = new StringBuffer(
						newAction.getProtocol() + "://" + newAction.getHost());
				if (newAction.getPort() != -1) {
					newUrlSb.append(":" + newAction.getPort());
				}
				if (newAction.getPath() != null) {
					newUrlSb.append(newAction.getPath());
				}
				if (newAction.getQuery() != null) {
					newUrlSb.append("?" + newAction.getQuery());
				}
				if (newAction.getRef() != null) {
					newUrlSb.append("#" + newAction.getRef());
				}

				return curl("POST", newUrlSb.toString(), paramMap,
						requestHeaderMap, isOnlyReturnHeader, path);
			} else if (responseCode == HttpURLConnection.HTTP_OK
					|| responseCode == HttpURLConnection.HTTP_CREATED) {
				byte[] bytes = new byte[0];
				if (!isOnlyReturnHeader) {
					if (isPost) {
						in = httpUrlConnection.getInputStream();
						ByteArrayOutputStream bout = new ByteArrayOutputStream();
						byte[] buf = new byte[1024];
						while (true) {
							int rc = in.read(buf);
							if (rc <= 0) {
								break;
							} else {
								bout.write(buf, 0, rc);
							}
						}
						bytes = bout.toByteArray();
						in.close();
					}
				}
				// only fetch Content-Length and Last-Modified header
				String encoding = null;
				if (encoding == null) {
					encoding = getEncodingFromContentType(httpUrlConnection
							.getHeaderField(CONTENT_TYPE));
				}
				content = new Content(sUrl, new String(bytes, encoding),
						httpUrlConnection.getHeaderFields());
			}
		} catch (Exception e) {
			return null;
		} finally {
			if (httpUrlConnection != null) {
				httpUrlConnection.disconnect();
			}
		}
		return content;
	}

	public static Content getRandom(String method, String sUrl,// 要解析的url
			Map<String, String> paramMap, // 存放用户名和密码的map
			Map<String, String> requestHeaderMap,// 存放COOKIE的map
			boolean isOnlyReturnHeader, String path) {

		Content content = null;
		HttpURLConnection httpUrlConnection = null;
		InputStream in = null;
		try {
			URL url = new URL(sUrl);
			boolean isPost = "POST".equals(method);
			if (method == null
					|| (!"GET".equalsIgnoreCase(method) && !"POST"
							.equalsIgnoreCase(method))) {
				method = "POST";
			}
			URL resolvedURL = url;
			URLConnection urlConnection = resolvedURL.openConnection();
			httpUrlConnection = (HttpURLConnection) urlConnection;
			httpUrlConnection.setRequestMethod(method);
			httpUrlConnection.setRequestProperty("Accept-Language",
					"zh-cn,zh;q=0.5");
			// Do not follow redirects, We will handle redirects ourself
			httpUrlConnection.setInstanceFollowRedirects(false);
			httpUrlConnection.setDoOutput(true);
			httpUrlConnection.setDoInput(true);
			httpUrlConnection.setConnectTimeout(5000);
			httpUrlConnection.setReadTimeout(5000);
			httpUrlConnection.setUseCaches(false);
			httpUrlConnection.setDefaultUseCaches(false);
			httpUrlConnection.connect();

			int responseCode = httpUrlConnection.getResponseCode();

			if (responseCode == HttpURLConnection.HTTP_OK
					|| responseCode == HttpURLConnection.HTTP_CREATED) {
				byte[] bytes = new byte[0];
				if (!isOnlyReturnHeader) {
					DataInputStream ins = new DataInputStream(
							httpUrlConnection.getInputStream());
					// 验证码的位置
					DataOutputStream out = new DataOutputStream(
							new FileOutputStream(path + "/code.bmp"));
					byte[] buffer = new byte[4096];
					int count = 0;
					while ((count = ins.read(buffer)) > 0) {
						out.write(buffer, 0, count);
					}
					out.close();
					ins.close();
				}
				String encoding = null;
				if (encoding == null) {
					encoding = getEncodingFromContentType(httpUrlConnection
							.getHeaderField(CONTENT_TYPE));
				}
				content = new Content(sUrl, new String(bytes, encoding),
						httpUrlConnection.getHeaderFields());
			}
		} catch (Exception e) {
			return null;
		} finally {
			if (httpUrlConnection != null) {
				httpUrlConnection.disconnect();
			}
		}
		return content;
	}

	public static String getEncodingFromContentType(String contentType) {
		String encoding = null;
		if (contentType == null) {
			return null;
		}
		StringTokenizer tok = new StringTokenizer(contentType, ";");
		if (tok.hasMoreTokens()) {
			tok.nextToken();
			while (tok.hasMoreTokens()) {
				String assignment = tok.nextToken().trim();
				int eqIdx = assignment.indexOf('=');
				if (eqIdx != -1) {
					String varName = assignment.substring(0, eqIdx).trim();
					if ("charset".equalsIgnoreCase(varName)) {
						String varValue = assignment.substring(eqIdx + 1)
								.trim();
						if (varValue.startsWith("\"")
								&& varValue.endsWith("\"")) {
							// substring works on indices
							varValue = varValue.substring(1,
									varValue.length() - 1);
						}
						if (Charset.isSupported(varValue)) {
							encoding = varValue;
						}
					}
				}
			}
		}
		if (encoding == null) {
			return "UTF-8";
		}
		return encoding;
	}

	// 这个是输出
	public static boolean inFile(String content, String path) {
		PrintWriter out = null;
		File file = new File(path);
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			out = new PrintWriter(new FileWriter(file));

			out.write(content);
			out.flush();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			out.close();
		}
		return false;
	}

	public static String getHtmlReadLine(String httpurl) {
		String CurrentLine = "";
		String TotalString = "";
		InputStream urlStream;
		String content = "";

		try {
			URL url = new URL(httpurl);

			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();

			connection.connect();
			System.out.println(connection.getResponseCode());
			urlStream = connection.getInputStream();

			BufferedReader reader = new BufferedReader(

			new InputStreamReader(urlStream, "utf-8"));

			while ((CurrentLine = reader.readLine()) != null) {
				TotalString += CurrentLine + "\n";
			}

			content = TotalString;

		} catch (Exception e) {
		}

		return content;
	}
}
